package com.autoagent.ai_live_master.webSocket.config;

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SocketIOConfig {

    private final SocketIOProperties properties;

    public SocketIOConfig(SocketIOProperties properties) {
        this.properties = properties;
    }

    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        // 添加更多socket优化
        socketConfig.setReuseAddress(true);
   
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname(properties.getHost());
        config.setPort(properties.getPort());
        config.setBossThreads(properties.getBossCount());
        config.setWorkerThreads(properties.getWorkCount());
        config.setAllowCustomRequests(properties.isAllowCustomRequests());
        config.setSocketConfig(socketConfig);
       
        // 关键修改：优化心跳配置
        config.setPingInterval(5000);   // 5秒心跳，适合浏览器
        config.setPingTimeout(15000);   // 15秒超时，给网络波动留时间
        
        // 传输配置：优先WebSocket，fallback到Polling
        config.setTransports(
            com.corundumstudio.socketio.Transport.WEBSOCKET, 
            com.corundumstudio.socketio.Transport.POLLING
        );
       
        // 缓冲区配置
        config.setMaxFramePayloadLength(65536);
        config.setMaxHttpContentLength(65536);
       
        // 连接配置
        config.setHttpCompression(true);
        config.setUpgradeTimeout(10000);
        config.setRandomSession(true);
        config.setAllowCustomRequests(true);
        config.setAllowHeaders("*");
        config.setOrigin("*");
        
        // 添加更宽松的连接配置
        config.setAckMode(com.corundumstudio.socketio.AckMode.AUTO_SUCCESS_ONLY);
        config.setStoreFactory(new com.corundumstudio.socketio.store.MemoryStoreFactory());
   
        return new SocketIOServer(config);
    }
}